package com.xuecheng.order.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xuecheng.commons.constants.OrdersConstants;
import com.xuecheng.commons.enums.ErrorCode;
import com.xuecheng.commons.model.vo.ResponseResult;
import com.xuecheng.order.config.PayTemplate;
import com.xuecheng.order.domain.Orders;
import com.xuecheng.order.domain.Payment;
import com.xuecheng.order.mapper.PaymentMapper;
import com.xuecheng.order.service.OrdersService;
import com.xuecheng.order.service.PaymentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.web.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 订单支付信息 服务实现类
 * </p>
 *
 * @author itheima
 * @since 2022-08-10
 */
@Service
public class PaymentServiceImpl extends ServiceImpl<PaymentMapper, Payment> implements PaymentService {

    
    @Autowired
    private OrdersService ordersService;

    @Autowired
    private PayTemplate payTemplate;
    
    // 生成支付连接
    @Override
    public ResponseResult createPay(String orderNo) {
        // 1.查询订单状态
        LambdaQueryWrapper<Orders> orderQw = new LambdaQueryWrapper<>();
        orderQw.eq(Orders::getOrderNo, orderNo);
        Orders orders = ordersService.getOne(orderQw);
        // 2.判断非初始状态全部拦截
        if (!orders.getStatus().equals(OrdersConstants.ORDER_INIT_STATUS)) {
            throw new BusinessException(ErrorCode.PAYERROR);
        }
        // 3.创建订单明细（跟订单一对一）
        LambdaQueryWrapper<Payment> payQw = new LambdaQueryWrapper<>();
        payQw.eq(Payment::getOrderNo,orderNo );
        Payment payment = this.getOne(payQw);
        if (payment==null) {
            payment = new Payment();
            payment.setUserId(orders.getUserId()); // 用户id
            payment.setCompanyId(orders.getCompanyId()); // 机构id
            payment.setOrderNo(orderNo);
            payment.setStatus(OrdersConstants.NOT_PAID.toString()); // 未支付
            payment.setPayMethod(OrdersConstants.PAY_METHOD_WX); // 支付方式
            payment.setReceiptAmount(orders.getPrice()); // 订单金额
            payment.setCreateDate(DateUtil.date()); // 创建时间
            this.save(payment);
        }
        // 4.调用微信工具类 生成支付连接
        String url = payTemplate.createOrder(orderNo, orders.getPrice(), orders.getCoursePubName()); // 订单号、商品价格、商品名称
        // 5.返回支付url
        return ResponseResult.okResult(url);
    }
}
